package com.stu.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HomeController {
    @RequestMapping({"/","/index"})//跳转到首页
    public String index(){ return "index"; }

    @RequestMapping("/toLogin")//跳转到登录页
    public String toLogin(){ return "login"; }

    @RequestMapping("/unAuthr")//跳转到未授权页面
    @ResponseBody
    public String unAuthorizedUrl(){ return "未授权无法访问该页面"; }

    @RequestMapping("/login")//登录
    public String login(String username,String password,Model model){
        Subject subject = SecurityUtils.getSubject();//获取当前用户
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);//封装用户登录数据
        try {
            subject.login(token);//登录
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","用户不存在");
            return "login";//登录失败
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "login";//登录失败
        }
        //登录成功
        //如果登录成功则在session中设置loginFlag。如果loginFlag为null，则显示登录选项，否则显示登出选项
        subject.getSession().setAttribute("loginFlag","hehe");
        return "redirect:/";//重定向到首页，如果是转发则url显示为login
    }

    @RequestMapping("/logout")//退出登录
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        subject.getSession().removeAttribute("loginFlag");//移除loginFlag
        return "redirect:/";//重定向到首页，如果是转发则url显示为logout
    }
}
